<template>
  <div class="active">
    <!-- 技术评审 -->
    <div
      style="display: flex; align-items: center; justify-content: space-between"
    >
      <h3>供应商技术评审总分</h3>
      <el-button type="primary" @click="getInfo(true)">刷新</el-button>
    </div>
    <el-table :data="summaryData" stripe style="width: 100%; margin-top: 20px">
      <el-table-column prop="key" label="序号" width="81" align="center" />
      <el-table-column
        prop="supplierCode"
        label="供应商编码"
        width="200"
        align="center"
      />
      <el-table-column
        prop="name"
        label="报名供应商"
        width="300"
        align="center"
      />
      <el-table-column
        :prop="item.name"
        :label="item.name"
        align="center"
        v-for="(item, index) in tablColumn"
        :key="index"
      >
        <template #default="scope">
          <div>{{ scope.row[item.name] }}</div>
        </template>
      </el-table-column>

      <el-table-column
        prop="averageScore"
        label="平均得分"
        width="100"
        align="center"
      />
    </el-table>

    <!-- 循环生成评委打分表 -->
    <div v-for="(table, index) in judgeBusiness" :key="index">
      <h3>{{ table.title }}</h3>
      <el-table
        :data="table.data"
        :span-method="objectSpanMethod"
        border
        style="width: 100%; margin-top: 20px"
      >
        <el-table-column prop="key" label="序号" width="81" align="center" />
        <el-table-column
          prop="supplierCode"
          label="供应商编码"
          width="200"
          align="center"
        />
        <el-table-column
          prop="name"
          label="报名供应商"
          width="300"
          align="center"
        />
        <el-table-column
          prop="evaluationPoint"
          label="考察要点"
          align="center"
        />
        <el-table-column prop="view" label="评分标准" align="center">
          <template #default="scope">
            <span class="link" @click="look(scope.row)">查看</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="score"
          :label="`评委${index + 1}打分`"
          width="120"
          align="center"
        >
          <template #default="scope">
            <div>{{ scope.row.score }}</div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="endbutton">
      <el-button @click="prevPage()">上一步</el-button>
      <el-button type="primary" @click="nextStep()">下一步</el-button>
    </div>
    <el-dialog v-model="dialogFormVisible" :title="title" width="500px">
      <div style="margin: 30px 30px 20px">
        {{ text }}
      </div>
      <template #footer>
        <div style="width: 100%; text-align: center">
          <el-button
            type="primary"
            @click="dialogFormVisible = false"
            style="padding: 20px 50px"
            >我知道了</el-button
          >
        </div>
      </template>
    </el-dialog>
    <div class="hidden-area" :style="{left:HiddenArea?'0':'-32%'}">
      <div v-if="!HiddenArea&&info.id" class="open" @click="HiddenArea=true"><img src="@/assets/right.png" alt="" class="icoButtom"></div>
      <div v-else class="hidden-div">
        <div @click="HiddenArea=false" class="close"><img src="@/assets/left.png" alt="" class="icoButtom"></div>
        <div class="hidden-info">
          <div v-if="info.id"  class="custom-scrollbar">
            <div class="info-logo">
              <img src="@/assets/2de0a0aed8c056d27f6076574092ce6.png" alt="" />
            </div>
            <biddingInfo :id="info.id" :judgeid="info.judgeid" :back="false"/>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { judgeProjectInfo } from "@/api/project.js";
import {
  getDictList,
  getDict,
  nowTime,
  getdict,
  SearchDicte,
} from "@/utils/common.js";
import {
  selectSupplierAndScore,
  selectGroupByMark,
  downBox,
  execTask,
} from "@/api/examine.js";
import { ElMessage } from "element-plus";
import biddingInfo from "./biddingInfo.vue";


const emit = defineEmits(["next-step"]);
const route = useRoute();
const router = useRouter();

const id = computed(() => route.query.id);
const props = defineProps({
  type: {
    type: String,
    required: true,
  },
});
const title = ref("");
const text = ref("");
const dialogFormVisible = ref(false);

const HiddenArea=ref(false)
const info=ref({})
const summaryData = ref([]);
const tablColumn = ref([]);
interface Supplier {
  id: number;
  supplierCode: string;
  name: string;
  evaluationPoint: string;
  score: number;
}
interface SpanMethodProps {
  row: Supplier;
  column: TableColumnCtx<Supplier>;
  rowIndex: number;
  columnIndex: number;
}
const rowspan = ref(1);
const objectSpanMethod = ({
  row,
  column,
  rowIndex,
  columnIndex,
}: SpanMethodProps) => {
  const key = column.property;

  if (key === "key" || key === "supplierCode" || key === "name") {
    if (rowIndex % rowspan.value === 0) {
      return {
        rowspan: rowspan.value,
        colspan: 1,
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0,
      };
    }
  }

  return { rowspan: 1, colspan: 1 };
};
const judgeBusiness = ref([]);
const getInfo = (boolean) => {
  selectSupplierAndScore({ projectId: id.value, type: "score_skill" }).then(
    (res) => {
      if (res.code == "200") {
        summaryData.value = [];
        tablColumn.value = [];
        const uniqueMarkNames = new Set();

        for (let i = 0; i < res.data.length; i++) {
          if (res.data[i].scoreList) {
            for (let j = 0; j < res.data[i].scoreList.length; j++) {
              const markName = res.data[i].scoreList[j].markName;

              // 如果 Set 中不存在这个 markName，则添加到 tablColumn.value 和 Set 中
              if (!uniqueMarkNames.has(markName)) {
                uniqueMarkNames.add(markName);
                tablColumn.value.push({
                  name: markName,
                });
              }
            }
          }
        }

        for (let i = 0; i < res.data.length; i++) {
          if (res.data[i].scoreList && res.data[i].scoreList.length > 0) {
            summaryData.value.push({
              key: i + 1,
              ...res.data[i],
            });
            console.log(1);

            if ([3, 5].includes(res.data[i].scoreList.length)) {
              assignScores(
                summaryData.value[i],
                res.data[i].scoreList,
                tablColumn
              );
            } else {
              console.log("评审数量有误");
            }
          }
        }

        if (boolean) {
          ElMessage({
            message: "刷新成功",
            type: "success",
          });
        }
      }
    }
  );

  selectGroupByMark({ projectId: id.value, type: "score_skill" }).then(
    (res) => {
      if (res.code == "200") {
        judgeBusiness.value = [];
        let supplierScores = {}; // 用于存储每个供应商在不同 markName 下的总分
        res.data.forEach((item) => {
          const markName = item.markName;
          const data = item.scoreDtoList.flatMap((subItem, subIndex) =>
            subItem.scoreList.map((innerItem) => ({
              id: innerItem.id,
              key: subIndex + 1,
              name: subItem.name,
              supplierCode: subItem.supplierCode,
              judgeid:subItem.applyId,
              view: innerItem.remark,
              evaluationPoint: innerItem.valueTitle,
              score:
                parseFloat(innerItem.score) != -1
                  ? parseFloat(innerItem.score)
                  : "请输入",
            }))
          );

          // 计算每个供应商的总分并存储在 supplierScores 中
          data.forEach((entry) => {
            if (!supplierScores[entry.supplierCode]) {
              supplierScores[entry.supplierCode] = {};
            }
            if (!supplierScores[entry.supplierCode][markName]) {
              supplierScores[entry.supplierCode][markName] = 0;
            }

            let Score = parseFloat(entry.score); // 尝试将score转换为浮点数
            if (isNaN(Score)) {
              supplierScores[entry.supplierCode][markName] = "待输入";
            } else {
              supplierScores[entry.supplierCode][markName] += entry.score;
            }
          });

          judgeBusiness.value.push({
            title: `供应商技术评审-${item.markName}打分`,
            data: data,
          });
        });

        summaryData.value.forEach((summaryEntry) => {
          let totalScore = 0;
          let count = 0; // 用于记录评分项的数量

          Object.keys(supplierScores[summaryEntry.supplierCode] || {}).forEach(
            (markName) => {
              const score =
                supplierScores[summaryEntry.supplierCode][markName] || 0;
              summaryEntry[markName] = score;
              if (totalScore == "待输入") {
                totalScore = "待输入";
              } else {
                totalScore += score;
              }
              count++; // 每处理一项就增加计数
              if (summaryEntry[markName] == "待输入") {
                totalScore = "待输入";
              }
            }
          );

          // 如果有评分项，则计算平均分；否则平均分为0
          summaryEntry.averageScore =
            totalScore != "待输入"
              ? count > 0
                ? (totalScore / count).toFixed(2)
                : 0
              : "待输入"; // 设置平均得分，并保留两位小数
        });
      }
    }
  );
  downBox({ projectId: id.value, type: "pdf_review_score_tech" }).then(
    (res) => {
      rowspan.value = res.data.length;
    }
  );
};

const look = (data) => {
  title.value = data.evaluationPoint;
  text.value = data.view;
  ClickRow(data);
  dialogFormVisible.value = true;
};
function calculateTotalScore(scoreList) {
  return scoreList.reduce((sum, item) => sum + parseFloat(item.score), 0);
}

function assignScores(summaryDataItem, scoreList, tablColumn) {
  scoreList.forEach((item, index) => {
    const columnName = tablColumn.value[index]?.name;
    if (columnName) {
      summaryDataItem[columnName] = parseFloat(item.score);
    }
  });

  // 如果没有现有的 totalScore，则计算它
  if (summaryDataItem.totalScore === undefined) {
    summaryDataItem.totalScore = calculateTotalScore(scoreList);
  }
}
const nextStep = () => {
  if (props.type == "taskSkill") {
    const params = { projectId: id.value };
    execTask(params).then((res) => {
      if (res.code) {
        window.location.replace("");
      }
    });
  } else {
    window.location.replace("");
    // emit("next-step", "taskEnd");
  }
};
const prevPage = () => {
  emit("next-step", "taskBusiness");
};
const ClickRow = (item) => {
  HiddenArea.value = false;
  setTimeout(() => {
    info.value = { id: id.value, judgeid: item.id };
    HiddenArea.value = true;
  }, 0); // 延迟1000毫秒（即1秒）
};
onMounted(() => {
  getInfo();
});
</script>
<style scoped lang="scss">
@use "./judge";
:deep(.el-input__inner) {
  text-align: center;
}
</style>
